using System;
using Qyoto;
using Clandestine.Graphics;
using Clandestine.Engines.Field;

namespace Shlick
{
	public class TilemapWidget : QFrame
	{
		public MapDocument MapDocument { get; private set; } 
		private Map Map { get { return this.MapDocument.Map; } } 
	
		private TilemapView view;
		private QComboBox tilemapsCombo;
		private QPushButton addButton;
		private QFrame frame;
		private QVBoxLayout vbox;
		private QHBoxLayout hbox;
		
		public TilemapWidget(MapDocument mapDocument) : base()
		{
			this.MapDocument = mapDocument;

			// Tie into Spritesheets list.
			this.Map.Spritesheets.SpritesheetAdd += onSpritesheetAdd;

			// Setup combo/button
			frame = new QFrame(this);
			frame.SetContentsMargins(0, 0, 0, 0);
			tilemapsCombo = new QComboBox(frame);
			addButton = new QPushButton(new QIcon(":/tango/scalable/actions/list-add.svg"), "", frame);
			addButton.ToolTip = "Add Tilemap";
			
			// And add them
			hbox = new QHBoxLayout(frame);
			hbox.Margin = 0;
			hbox.AddWidget(tilemapsCombo, 100); // 100 > 0, so tilemapsCombo stretches!
			hbox.AddWidget(addButton, 0);
			
			// Setup the View
			view = new TilemapView(this.MapDocument);
			vbox = new QVBoxLayout(this);
			vbox.Margin = 0;
			vbox.AddWidget(frame);
			vbox.AddWidget(view);
			
			// Signals
			Connect(tilemapsCombo, SIGNAL("currentIndexChanged(int)"), this, SLOT("comboChanged(int)"));
			Connect(addButton, SIGNAL("clicked()"), this, SLOT("addButtonClicked()"));
			
			// We will receive events for any future tilemaps loaded, but some might already be loaded!
			foreach (Spritesheet s in this.Map.Spritesheets)
				this.onSpritesheetAdd(s.Filename);
		}
		
		[Q_SLOT("addButtonClicked()")]
		private void addButtonClicked()
		{
			// Get a filename! Null if cancel selected.
			string filename = QFileDialog.GetOpenFileName(this, "Open New Tilemap", "", "Tilemaps (*.png *.jpg *.bmp)");
			if (string.IsNullOrEmpty(filename))
				return; // cancelled.
				
			// Load the tilemap with the map, they'll fire an event when they're done.
			this.Map.Spritesheets.LoadSpritesheet(filename);
		}
		
		[Q_SLOT("comboChanged(int)")]
		private void comboChanged(int i)
		{
			view.SetTilemap(tilemapsCombo.ItemText(i));
		}
		
		private void onSpritesheetAdd(string filename)
		{	
			// Add to the combo!
			tilemapsCombo.AddItem(filename);
			
			// If this is the first one, update the view
			//if (tilemapsCombo.Count == 1)
			//	comboChanged(filename);
		}
	}
}

